package org.shiro.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;

import java.util.Date;

/** @author LENOVO */
@Component
public class JwtUtil {
  /** 过期时间两分钟 */
  public static final long EXPIRE_TIME = 1000 * 60 * 2;
  /** 密钥 */
  private static final String SECRET = "27f01596480087cc507a443759141ad7";

  /**
   * 校验token是否正确
   *
   * @param token 密钥
   * @param username 用户名
   * @return 是否正确
   */
  public static boolean verify(String token, String username) {
    try {
      Algorithm algorithm = Algorithm.HMAC512(SECRET);
      JWTVerifier verifier = JWT.require(algorithm).withClaim("username", username).build();
      verifier.verify(token);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }
  /**
   * 获得token中的信息无需password解密也能获得
   *
   * @return token中包含的用户名
   */
  public static String getUsername(String token) {
    try {
      DecodedJWT jwt = JWT.decode(token);
      return jwt.getClaim("username").asString();
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
  /**
   * 生成签名,2分钟后过期
   *
   * @param username 用户名称
   * @param password 用户密码
   * @return 加密token
   */
  public static String sign(String username, String password) {
    try {
      Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
      Algorithm algorithm = Algorithm.HMAC512(SECRET);
      return JWT.create()
          .withClaim("username", username)
          .withExpiresAt(date)
          .withNotBefore(new Date())
          .sign(algorithm);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
}
